import React                            from 'react';
import ReactDOM                         from 'react-dom';
import cx                               from 'classnames';
import {connect}                        from 'react-redux';
import {Link}                           from 'react-router';
import Dropdown                         from 'rc-dropdown';
import Menu, {
	Item as MenuItem, Divider
}                                       from 'rc-menu';
import {
	removeNote, createNote, dropNote
}                                       from '../actions/note';
import {switchBookFromRemote}           from '../actions/book';

import Icon                             from './components/icons/index';
import Modal                            from './components/Modal';
import Loading                          from './components/Loading';
import Input                            from './components/Input';


import api from '../api';

import 'moment/locale/zh-cn';

moment.locale('zh-cn');

function sleep(time) {
	return new Promise((resolve) => setTimeout(resolve, time));
}

@connect(function (state, props) {
		return {
			books: state.book.items,
			bookId: state.book.current._id,
			selected: props.note._id == (state.note.current || {})._id
		};
	},
	{removeNote, dropNote})
class NoteItem extends React.Component {

	static contextTypes = {
		router: React.PropTypes.object
	};

	static propTypes = {
		dropNote: React.PropTypes.func,
		removeNote: React.PropTypes.func,
		bookId: React.PropTypes.string,
	};

	constructor(props) {
		super(props);
		let {index, count} = props;
		let lastTop = 50 + 85 * index;
		let spend = 0.2 + 0.05 * index;
		this.state = {
			lastTop: lastTop,
			spend: 0.2 + 0.05 * index,
			style: {
				top: lastTop + 85 * 2,
				transition: `top ${spend}s`
			}
		};
	}

	componentDidMount() {
		sleep(100).then(()=> {
			this.setState({
				style: {
					top: this.state.lastTop,
					transition: `top ${this.state.spend}s`
				}
			});
		});
	}

	componentWillReceiveProps(props) {
		if (props.index != this.props.index) {
			let {index} = props;
			let lastTop = 50 + 85 * index;
			let spend = 0.2 + 0.05 * index;
			this.setState({
				spend,
				lastTop,
				style: {
					top: lastTop,
					transition: `top ${spend}s`
				}
			});
		}
	}

	handleItemMore() {
		return (e) => {
			e.stopPropagation();
			e.preventDefault();
			this.setState({dropdown: true});
		}
	}

	handleItemShare(item) {

		let url = `${document.location.origin}/article/${item._id}`;
		let $input = void 0;
		let handleCopy = (e) => {
			e.stopPropagation();
			e.preventDefault();
			$input.focus();
			$input.setSelectionRange(0, url.length);
			document.execCommand("copy");
		};
		let handleInptRef = (input) => {
			$input = ReactDOM.findDOMNode(input);
			if ($input) $input.focus();
		};
		Modal.show(
			<div>
				<Input autoFocus defaultValue={url} ref={handleInptRef} style={{paddingRight: 80, width: '100%'}} type="text"/>
				<a href={url} onClick={handleCopy}
				   style={{display: 'inline-block', marginLeft: -80, width: 80, textAlign: 'center'}} target="_blank">
					复制
				</a>
			</div>
		);
	}

	handleItemRemove(item) {
		Modal.confirm("确定删除?", (close) => {
			this.props.removeNote(item);
			close();
		}, (close) => {
			close();
		});
	}

	handleItemDrop(item) {
		Modal.confirm("删除后无法恢复,确定删除?", (close) => {
			this.props.dropNote(item);
			close();
		}, (close) => {
			close();
		});
	}

	handleItemRestore(item) {
		api.putNote(item._id, {bookId: item.bookId}).then(() => {
			this.context.router.push(`/b-${item.bookId || 'recent'}/n-${item._id}`);
		});
	}

	handleItemMove(item) {
		let closeModal = Modal.show((
			<ul className="PopupSelection">
				{this.props.books.map((book) => (
					<li key={book._id} onClick={() => {
						moveBook(item._id, book._id);
					} }>{book.name}</li>
				)) }
			</ul>
		), () => {
			closeModal()
		});
		let moveBook = (noteId, bookId) => {
			let closeLoadingModal = Modal.show(<div><Loading/></div>);
			api.putNote(item._id, {bookId}).then(() => {
				closeLoadingModal();
				closeModal();
				this.context.router.push(`/b-${bookId}/n-${noteId}`);
			});
		}
	}

	handleItemDragStart(item) {
		return (e) => {
			e.stopPropagation();
			e.dataTransfer.setData("noteId", item._id);
		}
	}

	handleItemDragEnd() {
		return (e) => {
			e.stopPropagation();
		}
	}

	render() {
		let note = this.props.note;
		return (
			<li key={note._id} draggable={true}
			    style={this.state.style}
			    className={cx('NoteItem', {selected: this.props.selected}) }
			    onDragStart={this.handleItemDragStart(note) }
			    onDragEnd={this.handleItemDragEnd(note) }
			    onContextMenu={this.handleItemMore(note) }>
				<Link to={`/b-${this.props.bookId}/n-${note._id}`} className="title">
					<span className="text">{note.title}</span>
					<span className="actions">
            <Dropdown
	            visible={this.state.dropdown}
	            onVisibleChange={(v) => this.setState({dropdown: v}) }
	            trigger={['click']}
	            overlay={(
		            <Menu selectedKeys={[]} onClick={({key, domEvent}) => {
			            domEvent.stopPropagation();
			            domEvent.preventDefault();
			            this.setState({dropdown: false});
			            this[key](note);
		            } }>

			            <MenuItem key="handleItemShare">
				            <span >分享&nbsp; &nbsp; &nbsp; </span>
			            </MenuItem>
			            <MenuItem key="handleItemMove">
				            <span >移动到&nbsp; &nbsp; &nbsp; </span>
			            </MenuItem>
			            <Divider />
			            <MenuItem key="handleItemRemove" className={cx({hidden: note._delete}) }>
				            <span >删除&nbsp; &nbsp; &nbsp; </span>
			            </MenuItem>
			            <MenuItem key="handleItemRestore" className={cx({hidden: !note._delete}) }>
				            <span >恢复&nbsp; &nbsp; &nbsp; </span>
			            </MenuItem>
			            <MenuItem key="handleItemDrop" className={cx({hidden: !note._delete}) }>
				            <span >彻底删除&nbsp; &nbsp; &nbsp; </span>
			            </MenuItem>
		            </Menu>
	            ) }
	            animation="slide-up">
              <Icon type="arrow-down-b" className="more" style={{float: 'right'}}/>
            </Dropdown>
          </span>
				</Link>
				<div onClick={()=>this.context.router.push(`/b-${this.props.bookId}/n-${note._id}`)}>
					<date>{moment(note.dateUpdated).from(moment(new Date())) }</date>
				</div>
			</li>
		)
	}
}

@connect(function (state) {
	return {
		books: state.book.items,
		items: state.note.items,
		bookId: (state.book.current || {})._id,
		noteId: (state.note.current || {})._id
	};
}, {switchBookFromRemote, createNote})
export class NoteSelector extends React.Component {
	static propTypes = {
		name: React.PropTypes.string,
		params: React.PropTypes.object,
		dispatch: React.PropTypes.func,
		items: React.PropTypes.array,
		books: React.PropTypes.array,
		bookId: React.PropTypes.string,
		noteId: React.PropTypes.string,
	};

	static contextTypes = {
		store: React.PropTypes.object,
		router: React.PropTypes.object
	};

	constructor(props) {
		super(props);
		this.state = {
			searchKey: ''
		};
	}

	componentDidMount() {
		this.props.switchBookFromRemote(this.props.params.bookId);
	}

	componentWillReceiveProps(nextProps) {
		let {params} = this.props;
		if (params.bookId != nextProps.params.bookId) {
			this.props.switchBookFromRemote(nextProps.params.bookId);
		}
	}

	handleAddRandom() {
		this.props.createNote(this.props.bookId, "无标题笔记", "");
	}

	render() {
		let searchKey = this.state.searchKey.toUpperCase();
		let items = this.props.items.filter((item) => item.title.toUpperCase().indexOf(searchKey) >= 0);
		let itemsCount = items.length;
		let nodes = items.map((note, index) => <NoteItem key={`${note._id}`} note={note} index={index}
		                                                 count={itemsCount}/>);
		return (
			<div id="NoteSelector">
				<div className="SearchBox">
					<input type="text" className="SearchInput"
					       placeholder="搜索" value={this.state.searchKey}
					       onChange={(e) => this.setState({searchKey: e.target.value}) }/>
				</div>
				<ul className="NoteList">
					<li className="NoteItem" key={`top`} style={{height: 50}}>
						<Icon type="plus-round" onClick={this.handleAddRandom.bind(this) }/>
					</li>
					{ nodes }
				</ul>
			</div>
		);
	}
}

export default NoteSelector;